package com.example.demo.controller;



import com.example.demo.entity.User;
import com.example.demo.service.UserService;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.*;


//调用地址例如  http://localhost:8080/user/get/1

@RestController
@RequestMapping(value = "/user")
public class UserController {
    private static final int wdFormatPDF = 17;
    private static final int xlTypePDF = 0;
    private static final int ppSaveAsPDF = 32;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    @RequestMapping("/save")
    public void saveUser(User user){
        userService.save(user);
    }


    @RequestMapping("get/{id}")
    public User get(@PathVariable("id") String id){
        User user = userService.getUser(Integer.parseInt(id));
        logger.info("hello world");
        return user;
    }




    public static void main(String[] args) {

        try {
            //生成WORD问答盎
//            UserController.exportWord();
            UserController.wordToPdf("F:/1.doc","F:/2.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * word 转 pdf
     * @param fromAddress
     * @param toAddress
     */
    public static void wordToPdf(String fromAddress, String toAddress) {
        System.out.println("fromAddress=" + fromAddress);
        System.out.println("toAddress=" + toAddress);
        ActiveXComponent ax = null;
        try {
            long startTime = System.currentTimeMillis();
            /*
             * 创建不同的控件调用不同的值 Word——Word.Application Excel——Excel.Application
             * Powerpoint——Powerpoint.Application Outlook——Outlook.Application
             * wps 时用Kwps.Application
             */
            ax = new ActiveXComponent("Kwps.Application");
            /* 设置打开word文档不可见 */
            ax.setProperty("Visible", false);
            // 获取Word文档中所有内容
            Dispatch docs = ax.getProperty("Documents").toDispatch();
            // 打开word文档，并设置word为不可编辑和不需确认
            Dispatch doc = Dispatch.call(docs, "Open", fromAddress,// FileName
                    false,// ConfirmConversions
                    true // ReadOnly
            ).toDispatch();

            File tofile = new File(toAddress);
            if (tofile.exists()) {
                tofile.delete();
            }
            // word文件另存为pdf文件
            Dispatch.call(doc,//
                    "SaveAs", //
                    toAddress, // FileName
                    wdFormatPDF);
            // 关闭word文档
            Dispatch.call(doc, "Close", false);
            long endTime = System.currentTimeMillis();
            System.out.println("转化完成,总共耗时" + (endTime - startTime) + "ms。");
        } catch (Exception e) {
            System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally {
            if (ax != null)
                ax.invoke("Quit", new Variant[] {});
        }
    }

    /**
     * html 转化为word文档
     * @throws Exception
     */
    public static void exportWord() throws Exception {

        String body = "<h1 style=\"white-space: normal; text-align: center;\">\n" +
                "\t\t<strong><span style=\"font-family: 宋体; font-size: 29px;\">协查函</span></strong>\n" +
                "\t</h1>\n" +
                "\t<p style=\"white-space: normal; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">济宁市公安局：</span>\n" +
                "\t</p>\n" +
                "\t<p style=\"white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">我处在办理</span><span\n" +
                "\t\t\tstyle=\"font-family: 仿宋; line-height: 24px;\">案的过程中，需要身份证号码：370811198204263017的相关住宿信息。</span>\n" +
                "\t</p>\n" +
                "\t<p style=\"white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">特发此函，请贵单位协助提供资料。</span>\n" +
                "\t</p>\n" +
                "\t<p style=\"white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">&nbsp;</span>\n" +
                "\t</p>\n" +
                "\t<p style=\"white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">出函人：张玉翠</span>\n" +
                "\t</p>\n" +
                "\t<p style=\"white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">&nbsp;</span>\n" +
                "\t</p>\n" +
                "\t<p\n" +
                "\t\tstyle=\"margin-left: 420px; white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">&nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;嘉祥县院</span>\n" +
                "\t</p>\n" +
                "\t<p\n" +
                "\t\tstyle=\"margin-left: 420px; white-space: normal; text-indent: 28px; line-height: 24px;\">\n" +
                "\t\t<span style=\"font-family: 仿宋; line-height: 24px;\">&nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n" +
                "\t\t\t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2018-09-14</span>\n" +
                "\t</p>\n" +
                "\t<p>\n" +
                "\t\t<br />\n" +
                "\t</p>\n" +
                "\t\n" +
                "\t\n" +
                "\t<img src=\"'+CURRENT_APP_PATH+'/lbtb/zfsjzx/ywxt_xxcxlb/time.jpg\"><p style=\"margin-top: 10px;\">";

        //拼一个标准的HTML格式文档
        String content = "<html><head></head><body>" + body + "</body></html>";
        InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
        OutputStream os = new FileOutputStream("f:\\1.doc");
        UserController.inputStreamToWord(is, os);
    }
    /**
     * 把is写入到对应的word输出流os中
     * 不考虑异常的捕获，直接抛出
     * @param is
     * @param os
     * @throws IOException
     */
    private static void inputStreamToWord(InputStream is, OutputStream os) throws IOException {
        POIFSFileSystem fs = new POIFSFileSystem();
        //对应于org.apache.poi.hdf.extractor.WordDocument
        fs.createDocument(is, "WordDocument");
        fs.writeFilesystem(os);
        os.close();
        is.close();
    }

    /**
     * 把输入流里面的内容以UTF-8编码当文本取出。
     * 不考虑异常，直接抛出
     * @param ises
     * @return
     * @throws IOException
     */
    private String getContent(InputStream... ises) throws IOException {
        if (ises != null) {
            StringBuilder result = new StringBuilder();
            BufferedReader br;
            String line;
            for (InputStream is : ises) {
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line=br.readLine()) != null) {
                    result.append(line);
                }
            }
            return result.toString();
        }
        return null;
    }

}
